﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using YuuzleComic.DBUtility;
using System.Data.SqlClient;

public partial class yzadmin_data_chapter : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    private JObject result = new JObject();
    YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "delete":
                    this.ProcessDelete();
                    break;
                case "save":
                    this.ProcessSave();
                    break;
                case "allid":
                    this.ProcessAllId();
                    break;
                case "sort":
                    this.ProcessSort();
                    break;
                case "download":
                    this.ProcessDownload();
                    break;
                case "gettpadd":
                    this.ProcessGetTpadd();
                    break;
                case "rename":
                    this.ProcessRename();
                    break;
                case "savemulti":
                    this.ProcessSaveMulti();
                    break;
                case "cookie":
                    this.ProcessCookie();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessSaveMulti()
    {
        try
        {
            string zjmc = Request["zjmc"];
            int start = Convert.ToInt32(Request["start"]);
            string unit = Request["unit"];
            string[] zjids = Request["ids"].Split(',');
            Array.Reverse(zjids);
            int prefix = 0; 
            bool isPrefix = int.TryParse(zjmc,out prefix);
            foreach (string zjid in zjids)
            {
                YuuzleComic.Model.zj zj = zjbll.GetModel(int.Parse(zjid));
                string suffix = isPrefix ? zj.zjmc.Substring(prefix) : (string.IsNullOrEmpty(zjmc) ? "" : zj.zjmc.Substring(zj.zjmc.IndexOf(zjmc)));

                string newtpadd = zj.tpadd.Substring(0,zj.tpadd.LastIndexOf('/', zj.tpadd.Length - 2) + 1) + start + unit + "/";

                SqlParameter[] parameters = new SqlParameter[] { 
                    new SqlParameter("@zjmc", (start + unit + " " + suffix).Trim()),
                    new SqlParameter("@tpadd", newtpadd),
                    new SqlParameter("@id", zjid)
                };
                DbHelperSQL.ExecuteSql("update zj set zjmc=@zjmc,tpadd=@tpadd where id=@id", parameters);
                foreach (KeyValuePair<string, string> item in YuuzleComic.Config.verConfig.comicDatas)
                {
                    if (Directory.Exists(item.Value + zj.tpadd))
                    {
                        Directory.Move(item.Value + zj.tpadd, item.Value + newtpadd);
                        break;
                    }
                }
                start++;
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessCookie()
    {
        try
        {
            string tpadd = Request["tpadd"];
            string comicdata = string.Empty;
            foreach (KeyValuePair<string, string> item in YuuzleComic.Config.verConfig.comicDatas)
            {
                if (Directory.Exists(item.Value + tpadd))
                {
                    comicdata = item.Key;
                    Response.Cookies.Set(new HttpCookie("CKFinder:DynamicBaseUrl", comicdata));
                    break;
                }
            }
            if (string.IsNullOrEmpty(comicdata))
            {
                DbHelperSQL.ExecuteSql("update zj set isdownload=0 where tpadd=@tpadd", new SqlParameter[] { new SqlParameter("@tpadd", tpadd) });
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessRename()
    {
        try
        {
            List<YuuzleComic.Model.zj> zjlist = zjbll.GetModelList("id in (" + Request["zjid"] + ")");
            foreach (YuuzleComic.Model.zj zj in zjlist)
            {
                string path = "";
                string[] tpurlArr = zj.tpurl.Split('|');
                foreach (KeyValuePair<string, string> item in YuuzleComic.Config.verConfig.comicDatas)
                {
                    if (Directory.Exists(item.Value + zj.tpadd) && Directory.GetFiles(item.Value + zj.tpadd).Length >= tpurlArr.Length)
                    {
                        path = item.Value + zj.tpadd;
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(path))
                {
                    List<string> tpList = new List<string>();
                    for (int i = 0; i < tpurlArr.Length; i++)
	                {
                        FileInfo file = new FileInfo(path + tpurlArr[i].Substring(tpurlArr[i].LastIndexOf("/")));
                        if (file.Exists && file.Attributes != FileAttributes.System && file.Attributes != FileAttributes.Hidden)
                        {
                            string newName = file.Name;
                            if (!newName.Contains("yzmanga"))
	                        {
		                        newName = "yzmanga_" + String.Format("{0:D3}", i + 1) + "_" + Guid.NewGuid().ToString().Substring(0, 8) + file.Extension;
                                file.MoveTo(path + newName);
	                        }
                            tpList.Add(newName);
                        }
	                }
                    DbHelperSQL.ExecuteSql("update zj set tpurl='" + string.Join("|", tpList.ToArray()) + "' where id=" + zj.id);
                }
                result.Add("success", true);
            }
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessGetTpadd()
    {
        try
        {
            DataSet ds = DbHelperSQL.Query("select top(1) tpadd from zj where cid=" + Request["cid"]);
            if (ds.Tables[0].Rows.Count > 0)
            {
                string tpadd = ds.Tables[0].Rows[0][0].ToString();
                tpadd = tpadd.Substring(0, tpadd.LastIndexOf("/"));
                tpadd = tpadd.Substring(0, tpadd.LastIndexOf("/") + 1);
                result.Add("success", true);
                result.Add("value", tpadd);
            }
            else
            {
                result.Add("success", false);
            }
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessDownload()
    {
        try
        {
            if (!string.IsNullOrEmpty(Request["zjid"]))
            {
                DbHelperSQL.ExecuteSql("update zj set isdownload=0 where id in (" + Request["zjid"] + ")");
                result.Add("success", true);
            }
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessSort()
    {
        try
        {
            string sql = "";
            JArray data = JArray.Parse(Request.Form["data"]);
            foreach (JObject item in data)
            {
                sql += "update zj set ordernum=" + item["ordernum"] + " where id=" + item["id"] + ";";
            }
            DbHelperSQL.ExecuteSql(sql);
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }
    }

    private void ProcessAllId()
    {
        try
        {
            DataSet ds = DbHelperSQL.Query("select id from zj");
            List<int> idList = new List<int>();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                idList.Add(Convert.ToInt32(dr["id"]));
            }
            result.Add("success", true);
            result.Add("allid", JArray.FromObject(idList));
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessSave()
    {
        try
        {
            YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
            string oldtpadd = "";
            if (!string.IsNullOrEmpty(Request.Form["id"]))
            {
                zj = zjbll.GetModel(Convert.ToInt32(Request.Form["id"]));
                oldtpadd = zj.tpadd;
            }
            zj.zjmc=Request.Form["zjmc"];
            zj.tpadd=Request.Form["tpadd"];
            zj.tps = Convert.ToInt32(Request.Form["tps"]);
            zj.cid=Convert.ToInt32(Request.Form["cid"]);
            zj.tpurl = Request.Form["tpurl"];
            zj.time = DateTime.Now;
            if (string.IsNullOrEmpty(Request.Form["id"]))//如果章节id不存在就添加
	        {
                zj.isdownload = false;
                zj.cjitemid = -1;
                zjbll.Add(zj);
	        }
            else//否则就修改
            {
                zjbll.Update(zj);
                if (oldtpadd.ToLower() != zj.tpadd.ToLower() && Convert.ToInt32(DbHelperSQL.Query("select count(*) from zj where tpadd='" + oldtpadd + "' or tpadd='" + zj.tpadd + "'").Tables[0].Rows[0][0]) == 0)
                {
                    foreach (KeyValuePair<string, string> item in YuuzleComic.Config.verConfig.comicDatas)
                    {
                        if (Directory.Exists(item.Value + oldtpadd) && Directory.GetDirectories(item.Value + oldtpadd).Length == 0)
                        {
                            Directory.Move(item.Value + oldtpadd, item.Value + zj.tpadd);
                            break;
                        }
                    }
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessDelete()
    {
        try
        {
            DataSet ds = DbHelperSQL.Query("select cid,id,tpadd,hits from zj where id in (" + Request["ids"] + ")");
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (dr["hits"] != DBNull.Value && Convert.ToInt32(dr["hits"]) > 0)
                {
                    DbHelperSQL.ExecuteSql("update zj set hits=case when hits is null then " + Convert.ToInt32(dr["hits"]) + " else hits+" + Convert.ToInt32(dr["hits"]) + " end where id=(select top(1) id from zj where cid=" + dr["cid"] + " and id not in (" + Request["ids"] + ") order by id desc)");
                }
                string filename = Server.MapPath("~/comic/" + dr["cid"] + "/" + dr["id"] + ".html");
                if (File.Exists(filename))
                {
                    File.Delete(filename);
                }
                if (!string.IsNullOrEmpty(dr["tpadd"].ToString()) && Convert.ToInt32(DbHelperSQL.Query("select count(*) from zj where tpadd='" + dr["tpadd"] + "'").Tables[0].Rows[0][0]) == 1)
                {
                    foreach (KeyValuePair<string, string> item in YuuzleComic.Config.verConfig.comicDatas)
                    {
                        if (Directory.Exists(item.Value + dr["tpadd"]) && Directory.GetDirectories(item.Value + dr["tpadd"]).Length == 0)
                        {
                            Directory.Delete(item.Value + dr["tpadd"], true);
                        }
                    }
                }
            }
            DbHelperSQL.ExecuteSql("delete from zj where id in (" + Request["ids"] + ")");
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        json = result.ToString();
    }

    private void ProcessList()
    {
        try
        {
            DataTable dt = zjbll.GetList("cid=" + Request["cid"] + " order by ordernum desc").Tables[0];
            //dt.Columns.Add("directory");
            //foreach (DataRow dr in dt.Rows)
            //{
            //    dr["directory"] = "";
            //    foreach (KeyValuePair<string, string> item in YuuzleComic.Config.verConfig.comicDatas)
            //    {
            //        if (Directory.Exists(item.Value + dr["tpadd"]))
            //        {
            //            dr["directory"] = item.Key;
            //            break;
            //        }
            //    }
            //    if (string.IsNullOrEmpty(dr["directory"].ToString()))
            //    {
            //        //DbHelperSQL.ExecuteSql("update zj set isdownload=0 where id=" + dr["id"]);
            //    }
            //}
            JsonSerializer serializer = new JsonSerializer();
            serializer.Converters.Add(new JavaScriptDateTimeConverter());
            serializer.NullValueHandling = NullValueHandling.Ignore;
            result.Add("data", JArray.FromObject(dt, serializer));
            result.Add("total", dt.Rows.Count);
            json = result.ToString();
        }
        catch (Exception)
        {
            
            throw;
        }
        
    }
}